//
//  STAllCommodityController.swift
//  iPhone
//
//  Created by Toj on 8/9/22.
//

import UIKit

class STAllCommodityController: STBaseCommodityController {
    
    public let viewModel = STCommodityAllViewModel()
    
    private var sectionModels: [STCommodityAllSectionModel] = [] { didSet {
        notDataView.isHidden = !sectionModels.isEmpty
        collectionView.reloadData()
    } }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupCollectionView()
        
        setupRequestAllProducts()
        
        requestAllProducts()
    }
    
    override func registerCollectionViews() {
        super.registerCollectionViews()
        collectionView.register(CommodityTVCell.cell_class, forCellWithReuseIdentifier: CommodityTVCell.cell_identifier)
        collectionView.register(CommodityMobileCell.cell_class, forCellWithReuseIdentifier: CommodityMobileCell.cell_identifier)
    }
    
    private func setupCollectionView() {
        
        bottomOffset = headerViewHeight
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    internal override func reloadHeaderInfo() {
        headerView?.setMembershipInfo(segmentType: type, product: nil)
    }
    
    internal override func reloadInfo() {
        
    }
    
    deinit {
        print("-->toj: STAllCommodityController: deinit")
        NotificationCenter.default.removeObserver(self)
    }
}

extension STAllCommodityController {
    
    private func setupRequestAllProducts() {
        viewModel.allProductRequest = { [weak self] sections in
            self?.view.hud.hide()
            self?.sectionModels = sections
        }
        
        viewModel.requestAllProductsLoading = { [weak self] in
            self?.view.hud.enabled(false).show()
        }
    }
    
    private func requestAllProducts() {
        view.hud.enabled(false).show()
        viewModel.requestAllProducts { [weak self] sections in
            self?.view.hud.hide()
            self?.sectionModels = sections
        }
    }
}

extension STAllCommodityController: UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return sectionModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let sectionModel = sectionModels[section]
        
        if sectionModel.type == .tv {
            return 1
        }
        
        return sectionModel.products?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let sectionModel = sectionModels[indexPath.section]
        
        if sectionModel.type == .tv {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CommodityTVCell.cell_identifier, for: indexPath, CommodityTVCell.self)
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CommodityMobileCell.cell_identifier, for: indexPath, CommodityMobileCell.self)
        let model = sectionModel.products?[indexPath.row]
        cell.productModel = model
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let sectionModel = sectionModels[indexPath.section]
        if kind == UICollectionView.elementKindSectionHeader {
            let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: CommodityTitleView.cell_identifier, for: indexPath) as? CommodityTitleView
            view?.section = sectionModel
            return view!
        }
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: UICollectionReusableView.cell_identifier, for: indexPath)
        view.backgroundColor = "#EEEEEE".to_color
        return view
    }
    
   func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let sectionModel = sectionModels[indexPath.section]
        if sectionModel.type == .tv {
            commodityDelegate?.commodityController(self, didSelectedProductType: .tv)
            return
        }
        
       if sectionModel.type == .bundleProduce {
           guard let product = sectionModel.products?[indexPath.row] else { return }
           viewModel.ds_didTapDataBundleInfo(id: "\(product.id)")
           STSRouter.openURLString(product.link)
           return
       }
       
       guard let product = sectionModel.products?[indexPath.row] else { return }
       viewModel.didTapProductHandle?(product)
       commodityDelegate?.commodityController(self, didSelectedProductType: .mobile)
       
       viewModel.ds_didTapProduct(product: product)
   }
}

extension STAllCommodityController: UICollectionViewDelegateFlowLayout {
    
    // section 上下左右的间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 12, bottom: 12, right: 12)
    }
    
    // cell 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let scale = (STScreenWidth-24) / 336
        
        let section = sectionModels[indexPath.section]
        if section.type == .tv {
            let height = scale * 88
            return CGSize(width: STScreenWidth-24, height: height)
        }
        
        let height = scale * 64
        return CGSize(width: STScreenWidth-24, height: height)
     
    }
    
    // section header 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
//        let section = viewModel.sections[section]
       
        return CGSize(width: STScreenWidth, height: 52)
    }
    
    // section footer 大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        
        if section == collectionView.numberOfSections-1 {
            return STDefaultCellSize
        }
        return CGSize(width: STScreenWidth, height: 8)
    }
    
    // cell之间 垂直间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 12
    }

    // cell之间 水平间距
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.01
    }
}
